package org.wattdepot.cli.command;

import java.util.ArrayList;
import java.util.List;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.cli.CommandLineInterface;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.resource.source.jaxb.Source;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * Returns the total power generated by the given fuel type.
 * 
 * @author Anthony Xu & John Mack
 *
 */
public class TotalpowerCommand implements WattDepotCliCommand {
  
  /**
   * Returns the total power generated by the given fuel type.
   * 
   * @param cli WattDepotClient with hostUri = http://server.wattdepot.org:8182/wattdepot/
   * @param commands user's command line input
   * @return string to output
   */
  public String doCommand(CommandLineInterface cli, List<String> commands) {   
    String str = "";
    double totalPower = 0;
    ArrayList<Source> sourceList = new ArrayList<Source>();
    try {
      String fuel = commands.get(3);
      Source source = cli.getClient().getSource(commands.get(1));
      XMLGregorianCalendar timestamp = Tstamp.makeTimestamp(commands.get(2));
      sourceList.add(source);
      int sourceCount = 0;
      while (sourceCount < sourceList.size()) {
        if (sourceList.get(sourceCount).isVirtual()) {
          List<String> children = source.getSubSources().getHref();
          for (int i = 0; i < children.size(); i++) {
            String url = children.get(i);
            String sourceName = url.substring(url.lastIndexOf('/') + 1);
            Source subsource = cli.getClient().getSource(sourceName);
            sourceList.add(subsource);
          }
          sourceList.remove(sourceCount);
        }
        else {
          sourceCount++;
        }
      }
      for (int j = 0; j < sourceList.size(); j++) {
        if (fuel.compareTo(sourceList.get(j).getProperty("fuelType")) == 0) {
          sourceList.remove(j);
        }
      }
      for (int k = 0; k < sourceList.size(); k++) {
        totalPower += cli.getClient().getPowerGenerated(sourceList.get(k).getName(), timestamp);
      }
      totalPower = totalPower / 1000000;
      str += Double.toString(totalPower);
    }
    catch (NotAuthorizedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch (ResourceNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch (BadXmlException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch (MiscClientException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch (Exception e) {
      // timestamp
      e.printStackTrace();
    }
    return str;
  }

}
